package com.xuan.system.controller;


import com.xuan.common.core.constants.HttpConstants;
import com.xuan.common.core.controller.BaseController;
import com.xuan.common.core.domain.R;
import com.xuan.system.domain.sysUser.dto.LoginSysUserDTO;
import com.xuan.system.domain.sysUser.entity.SysUser;
import com.xuan.system.domain.sysUser.vo.SysUserVo;
import com.xuan.system.service.sysUser.SysUserService;
import com.xuan.system.utils.BCryptUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/sysUser")
@Slf4j
@Tag(name = "管理员API")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Operation(summary = "新增管理员", description = "根据提供的信息新增管理员用户")
    @ApiResponse(responseCode = "1000", description = "操作成功")
    @ApiResponse(responseCode = "2000", description = "服务繁忙请稍后重试")
    @ApiResponse(responseCode = "3101", description = "⽤⼾已存在")
    @PostMapping("/add")
    public R<Void> add(String userAccount, String password) {
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(userAccount);
        sysUser.setPassword(BCryptUtils.encryptPassword(password));
        sysUser.setCreateBy(1L);
        boolean save = sysUserService.save(sysUser);
        return toR(save);
    }

    @Operation(summary = "管理员登录", description = "根据账户和密码登录")
    @Parameters(@Parameter(name = "LoginSysUserDTO", description = "登录所需条件"))
    @ApiResponse(responseCode = "1000", description = "登录成功")
    @ApiResponse(responseCode = "3002", description = "参数校验失败")
    @ApiResponse(responseCode = "3102", description = "用户不存在")
    @ApiResponse(responseCode = "3103", description = "用户名或密码错误")
    @PostMapping("/login")
    public R<String> login(@RequestBody LoginSysUserDTO loginSysUserDTO) {
        if (loginSysUserDTO == null) {
            return R.fail("参数为空");
        }

        return sysUserService.login(loginSysUserDTO);
    }

    @DeleteMapping("/logout")
    public R<Void> logout(@RequestHeader(HttpConstants.AUTHENTICATION) String token) {
        if (token == null) {
            return R.fail("当前处于未登录状态");
        }
        return toR(sysUserService.logout(token));
    }

    @GetMapping("/info")
    public R<SysUserVo> getLoginUser(@RequestHeader(HttpConstants.AUTHENTICATION) String token) {
        if (token == null) {
            return R.fail("当前处于未登录状态");
        }
        return R.ok(sysUserService.getUserInfo(token));
    }

}
